package practica3as;

import entities.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class PhaseConnection implements PhaseLoader{
    private String sessionID = "";
    
    public URLConnection getConnection() {
        URLConnection urlConnection = null;
        String location = "http://localhost:8084/Practica3asServer/PhaseServlet";
        try {
            URL url = new URL(location);
            urlConnection = url.openConnection();
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setUseCaches(false);
            urlConnection.setRequestProperty("Content-Type", "application/x-java-serialized-object");
        } catch (IOException ex) {
            
        }
        return urlConnection;
    }
    
    @Override
    public Drawable loadPhase(int p) {
        try{
            URLConnection connection = getConnection();
            OutputStream outputStream = connection.getOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            
            objectOutputStream.writeObject(true);
            objectOutputStream.flush();
            objectOutputStream.close();
            
            InputStream inputStream = connection.getInputStream();
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
            sessionID = (String) objectInputStream.readObject();
            Composite c = (Composite) objectInputStream.readObject();
            return c;
        }
        catch (Exception e){
            
        }
        return null;
    }
}
